import {
  Controller,
  All,
  Body,
  Query,
  Req,
  Res,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { ApiGatewayService } from './api-gateway.service';
import { Request, Response } from 'express';
import { cryptoMd5 } from '@app/utils';
// @app/common
import { IP, IsPublic } from '@app/common';

@Controller()
@IsPublic()
export class ApiGatewayController {
  constructor(private readonly apiGatewayService: ApiGatewayService) {}

  @All()
  get(@IP() ip: string, @Req() req: Request) {
    return {
      time: Date.now(),
      ip,
      headers: req.headers,
    };
  }

  @All('/webhook')
  @HttpCode(HttpStatus.OK)
  webhook(@Body() data: any, @Query() query: any, @Res() res: Response) {
    const requestBody = {
      ...data,
      ...query,
    };
    if (!requestBody?.timestamp) {
      res.status(HttpStatus.OK).send('failed');
      return;
    }
    // 签名校验
    const sign = cryptoMd5(
      requestBody?.timestamp + cryptoMd5('kYGx00CwCVYy3rtr38GgEoP5GB6ITX0w'),
    );
    if (sign !== requestBody?.sign) {
      res.status(HttpStatus.OK).send('sign failed');
      return;
    }
    // 这里需要直接输出
    res.status(HttpStatus.OK).send('success');
    return;
  }
}
